package com.briup.estore.common.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.briup.estore.common.constant.AliPayConstant;

import java.util.Objects;

/**
 * 支付宝支付配置类
 */
public class ALiPayUtils {

    private static AlipayClient alipayClient = null;

    //获取阿里支付客户端对象
    private static AlipayClient getALiPayClient() {
        if (Objects.isNull(alipayClient))
            alipayClient = new DefaultAlipayClient(AliPayConstant.SERVER_URL, AliPayConstant.APP_ID, AliPayConstant.APP_PRIVATE_KEY, AliPayConstant.FORMAT, AliPayConstant.CHARSET, AliPayConstant.ALIPAY_PUBLIC_KEY, AliPayConstant.SIGN_TYPE);

        return alipayClient;
    }

    public  static String  pay(String orderId,String totalPrice,String callBackUrl){
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        //订单支付
        model.setBody("订单描述：杰普网上书城购物订单");
        //订单名字
        model.setSubject("杰普书城购物订单");
        //订单号
        model.setOutTradeNo(orderId);
        //过期时间
        model.setTimeoutExpress("30m");
        //订单金额
        model.setTotalAmount(totalPrice);
        //产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        //设置参数
        alipayTradePagePayRequest.setBizModel(model);
        //回调地址
        alipayTradePagePayRequest.setReturnUrl(callBackUrl);
        //客户端执行,拿到支付结果
        AlipayTradePagePayResponse pageExecute = null;
        try {
            pageExecute = alipayClient.pageExecute(alipayTradePagePayRequest);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return  pageExecute.getBody();
    }
}
